// pages/my-realname/my-realname.js
const app = getApp();
const db = wx.cloud.database().collection("audit")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sname:'',
    studentID:'',
    imgUrl:'',
    authen:0
  },
  onLoad: function (options) {
    // Query user table to check authentication status
    wx.cloud.database().collection("user").where({
      _openid: app.globalData.user_openid // Assuming you store openid in globalData
    }).get().then(res => {
      if (res.data && res.data.length > 0) {
        const userInfo = res.data[0];
        this.setData({ 
          authen: userInfo.authen });
  
        if (userInfo.authen === 1 || userInfo.authen === 2 || userInfo.authen === 3) {
          console.log(app.globalData.user_openid)
          db.where({
            _openid: app.globalData.user_openid // Assuming you store openid in globalData
          }).get().then(res => {
            if (res.data && res.data.length > 0) {
              const auditInfo = res.data[0];
              // Update the data to be displayed on the page
              this.setData({
                sname: auditInfo.name,
                studentID: auditInfo.sid,
                imgUrl: auditInfo.picture_url
              });
            }
          }).catch(err => {
            console.error('查询审核信息失败：', err);
          });
        }
      }
    }).catch(err => {
      console.error('查询用户信息失败：', err);
    });
  },
  

  handleUpload() {
    let that = this;
    let timestamp = (new Date()).valueOf();
    wx.chooseImage({
     success: chooseResult => {
      wx.showLoading({
       title: '上传中',
      })
      // 将图片上传至云存储空间
      wx.cloud.uploadFile({
       // 指定上传到的云路径
       cloudPath: 'audit/'+timestamp + '.png',
       // 指定要上传的文件的小程序临时文件路径
       filePath: chooseResult.tempFilePaths[0],
       // 成功回调
       success: res => {
        console.log('上传成功', res)
        wx.hideLoading()
        wx.showToast({
         title: '上传图片成功',
        })
        if (res.fileID) {
         that.setData({
          zhaopian: '图片如下',
          imgUrl: res.fileID
         })
        }
  
       },
      })
     },
    })
    },
    submit() {
      const { sname, studentID, imgUrl } = this.data;
    
      if (!sname || !studentID || !imgUrl) {
        wx.showToast({
          title: '请填写完整信息',
          icon: 'error'
        });
        return;
      }
      // 如果 authen 为 3，则修改用户表中的 authen 字段
  if (this.data.authen === 3) {
    db.where({
      _openid: app.globalData.user_openid
    }).update({
      data: {
        name: sname,
              picture_url: imgUrl,
              sid: studentID,
              type: 0
      }
    }).then(res => {
      console.log('数据更新成功', res);
      // 更新成功后重新加载页面数据

      wx.cloud.database().collection("user").where({
          _openid: app.globalData.user_openid // Assuming you store openid in globalData
        }).update({
          data: {
            authen: 1
          }
        }).then(() => {
          console.log('authen更新成功');
          this.onLoad();
        }).catch(err => {
          console.error('authen更新失败', err);
        });
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });
    }).catch(err => {
      console.error('数据更新失败', err);
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
    });
  }
  else if (this.data.authen === 0) {
      
      db.where({
        name: sname,
        sid: studentID
      }).get().then(res => {
        if (res.data.length > 0) {
          const existingData = res.data[0];
          if (existingData.type) {
            wx.showToast({
              title: '信息已被认证过',
              icon: 'none'
            });
          } else {
            wx.showToast({
              title: '该信息正在审核中，请勿重复提交',
              icon: 'none'
            });
          }
        } else {
          db.add({
            data: {
              name: sname,
              picture_url: imgUrl,
              sid: studentID,
              type: 0
            }
          }).then(res => {
            console.log('数据添加成功', res);
            // After successful submission, update the authen field in the user table
        wx.cloud.database().collection("user").where({
          _openid: app.globalData.user_openid // Assuming you store openid in globalData
        }).update({
          data: {
            authen: 1
          }
        }).then(() => {
          console.log('authen更新成功');
          this.onLoad();
        }).catch(err => {
          console.error('authen更新失败', err);
        });

        wx.showToast({
          title: '提交成功',
          icon: 'success'
        });
          }).catch(err => {
            console.error('数据添加失败', err);
            wx.showToast({
              title: '提交失败，请重试',
              icon: 'none'
            });
          });
        }
      }).catch(err => {
        console.error('查询失败', err);
        wx.showToast({
          title: '查询失败，请重试',
          icon: 'none'
        });
      });
    }
  }
    

})